use std::fmt::{Display, Formatter, write};
use std::rc::Rc;
use crate::{Link, List, Node};
// 这是
//list1 -> A ---+
//               |
//               v
// list2 ------> B -> C -> D
//               ^
//               |
// list3 -> X ---+


//共享所有权的链表
#[derive(Debug, Clone)]
pub struct RcNode<T> {
    elem: T,
    next: RcLink<T>,
}

type RcLink<T> = Option<Rc<RcNode<T>>>;

#[derive(Debug, Clone)]
pub struct RcList<T> {
    head: RcLink<T>,
}

impl<T> RcList<T> {
    pub fn new() -> Self {
        RcList {
            head: RcLink::None
        }
    }

    // 追加
    pub fn append(&mut self, ele: T) -> RcList<T> {
        // let xx =self.head.clone() ;
        RcList {
            head: Some(Rc::new(RcNode {
                elem: ele,
                next: self.head.clone(),  //   node 是Rc 类型， clone 只是引用计数加1，
            }))
        }
    }


    // 去掉头元素， 返回剩下的元素
    pub fn tail(&self) -> RcList<T> {
        match self.head.as_ref() {
            Some(n) => {
                RcList {
                    head: n.next.clone()
                }
            }
            _ => { RcList::new() }
        }
    }


    pub fn head(&self) -> Option<&T> {

        // as_ref() 得到引用对象
        // map() 的作用是转换数据 , map的入参是闭包
        //  head  是 Option<Rc<RcNode<T>>> ， as_ref()  返回的是Option<&Rc<RcNode<T>>>
        // option 类型的map 方法 是数据转换，

        let temp = self.head.as_ref();
        temp.map(|node| {
            // node  是option 里面的参数 ,也就是 &Rc<RcNode<T>>
            let head_value = &(node.elem);
            head_value
        })
    }
}


// IntoIter - T    无法实现
// IterMut - &mut T   无法实现
// Iter - &T

pub struct Iter<'a, T> {
    next: Option<&'a RcNode<T>>,
}


impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        // todo!()
        self.next.map(|node| {
            self.next = node.next.as_deref();
            &node.elem
        })
    }
}


impl<T> RcList<T> {
    pub fn iter(&self) -> Iter<T> {
        Iter {
            next: self.head.as_deref()
        }
    }
}


// 实现Drop 销毁对象的时候才调用
impl<T> Drop for RcList<T> {
    fn drop(&mut self) {
        let mut head = self.head.take();


        while let Some(mut node) = head {
            if let Ok(mut node) = Rc::try_unwrap(node) {
                let value = node.elem;

                println!("销毁中....");
                head = node.next.take()
            } else {
                println!("当前node还有引用,无法销毁");
                break;
            }
        }
    }
}


// cargo  test  rc_linked_list
#[cfg(test)]
mod test {
    use std::thread;
    use std::thread::Thread;
    use std::time::Duration;
    use crate::rc_linked_list::{RcLink, RcList, RcNode};

    #[test]
    fn test_append() {
        let mut list1 = RcList::new();

        let mut list1 = list1.append(1);

        println!("list1 is {:?}", list1);

        let mut list1 = list1.append(2);

        println!("list1 is {:?}", list1);
    }


    // 链式调用
    #[test]
    fn test_append2() {
        let mut list1 = RcList::new();

        let mut list1 = list1.append(1).append(2).append(3);
        println!("list1 is {:?}", list1);
    }


    #[test]
    fn test_head() {
        let mut list1 = RcList::new();

        println!("list1.head  is {:?}", list1.head());

        let mut list1 = list1.append(1);

        println!("list1.head  is {:?}", list1.head());

        let mut list1 = list1.append(2);

        println!("list1.head  is {:?}", list1.head());
    }


    #[test]
    fn test_tail() {
        let mut list1 = RcList::new();

        let mut list1 = list1.append(1).append(2).append(3);
        println!("list1 is {:?}", list1); // 结构是(3->2->1->None)

        let mut list1 = list1.tail();
        println!("list1 is {:?}", list1); // 结构是(2->1->None)
    }


    #[test]
    fn test_tail2() {
        let mut list1: RcList<i32> = RcList::new();
        println!("list1 is {:?}", list1); // 结构是(None)

        let list1 = list1.tail();
        println!("list1 is {:?}", list1); // 结构是(None)
    }


    #[test]
    fn test_iter() {
        let mut list1 = RcList::new();

        let mut list1 = list1.append(1).append(2).append(3);

        let mut iter = list1.iter();

        assert_eq!(iter.next(), Some(&3));
        assert_eq!(iter.next(), Some(&2));
        assert_eq!(iter.next(), Some(&1));
        assert_eq!(iter.next(), None);
    }


    #[test]
    fn test_drop() {
        let mut list1 = RcList::new();

        let mut list1 = list1.append(1).append(2).append(3);


        {
            let list2 = list1.append(333);
        } // 333 会销毁



        println!("++++++++++++++++++++++++++++++");
    }
}